<?php

namespace App\Http\Controllers;

use App\Models\Type;
use App\Models\OperationLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TypeController extends Controller
{
    /**
     * 显示材料类型列表
     */
    public function index()
    {
        $types = Type::paginate(10);
        return view('types.index', compact('types'));
    }

    /**
     * 创建新材料类型
     */
    public function create()
    {
        return view('types.create');
    }

    /**
     * 保存新创建的材料类型
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:50|unique:types',
            'description' => 'nullable|string|max:200'
        ]);

        $type = Type::create($request->all());

        // 记录操作日志
        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'create',
            'target_type' => 'type',
            'target_id' => $type->id,
            'content' => "创建材料类型：{$type->name}",
            'ip' => $request->ip()
        ]);

        return redirect()->route('types.index')->with('success', '材料类型创建成功');
    }

    /**
     * 编辑材料类型
     */
    public function edit(Type $type)
    {
        return view('types.edit', compact('type'));
    }

    /**
     * 更新材料类型
     */
    public function update(Request $request, Type $type)
    {
        $request->validate([
            'name' => 'required|string|max:50|unique:types,name,' . $type->id,
            'description' => 'nullable|string|max:200'
        ]);

        $type->update($request->all());

        // 记录操作日志
        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'update',
            'target_type' => 'type',
            'target_id' => $type->id,
            'content' => "更新材料类型：{$type->name}",
            'ip' => $request->ip()
        ]);

        return redirect()->route('types.index')->with('success', '材料类型更新成功');
    }

    /**
     * 删除材料类型
     */
    public function destroy(Type $type)
    {
        // 检查是否有关联的材料
        if ($type->materials()->exists()) {
            return redirect()->route('types.index')
                ->with('error', '该类型下存在材料，无法删除');
        }

        // 记录操作日志
        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'delete',
            'target_type' => 'type',
            'target_id' => $type->id,
            'content' => "删除材料类型：{$type->name}",
            'ip' => request()->ip()
        ]);

        $type->delete();

        return redirect()->route('types.index')->with('success', '材料类型删除成功');
    }
} 